import 'dart:convert';
import 'package:base_flutter/base_flutter.dart' as b;
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker_fork/flutter_cupertino_date_picker_fork.dart';
import 'package:ls_work/a_elder/models/waiting_list_entity.dart';
import 'package:ls_work/a_elder/models/waiting_right_entity.dart';
import 'package:ls_work/a_yyt/models/medical_service_entity.dart';
import 'package:ls_work/a_yyt/models/pending_entity.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/toast.dart';

import '../../widgets/out_line_button.dart';





class HomePendingbatchExecutionPage extends StatefulWidget {
  final LeftValue? elderInfo;
  final List<WaitingRighInfo>? rightDataList;
  final VoidCallback? callBack;
  HomePendingbatchExecutionPage({
    Key? key,
    this.elderInfo,
    this.rightDataList,
    this.callBack,
  });
  @override
  _HomePendingbatchExecutionPageState createState() =>
      _HomePendingbatchExecutionPageState();
}

class _HomePendingbatchExecutionPageState
    extends State<HomePendingbatchExecutionPage> {
  List<TextEditingController> textEditingControllers = [];
  bool allSelectrd = false;
  List<MedicaServiceInfo> selectedDataList = [];
  List<MedicaServiceInfo> dataList = [];
  String ids = "";

  @override
  void initState() {
    super.initState();
    var temp = [];
    for (var item in( widget.rightDataList??<WaitingRighInfo>[])) {
      temp.add(item.bizId);
    }
    ids = temp.join(",");
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _fectData();
    });
  }

  _executeServicePlanRecordBatch() {
    if (selectedDataList.length <= 0) {
      Toast.show("请选择至少一项服务");
      return;
    }

    List tempList = [];
    for (var item in selectedDataList) {
      Map<String, dynamic> map = {};
      map["id"] = item.id;
      map["executeStatus"] = 0;
      map["finishTime"] =
          DateUtil.formatDate(item.dateTime, format: DateFormats.full);
      map["remark"] = item.itemRemark;
      if ((item.result??[]).length > 0) {
        var temp = [];
        for (var i = 0; i < (item.result?.length??0); i++) {
          print(item.result![i].textEditingController);
          temp.add({
            'value': item.result![i].textEditingController?.text,
            'rangeTo': item.result![i].rangeTo ?? "",
            'rangeFrom': item.result![i].rangeFrom ?? "",
            'subItem': item.result![i].subItem,
          });
        }
        map['result'] = jsonEncode(temp);
      }
      tempList.add(map);
    }
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post(
          "${HttpApi.executeServicePlanRecordBatch}?jsonStr=${jsonEncode(tempList)}",
        )
        .then((r) {
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          Toast.show(map["msg"]);
          if(widget.callBack!=null){
            widget.callBack!();
          }
          Navigator.pop(context);
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("${widget.elderInfo?.elderName ?? "待办"}"),
        elevation: 0.5,
        actions: [
          TextButton(
            onPressed: _executeServicePlanRecordBatch,
            child: Text("提交"),
          ),
        ],
      ),
      body: Container(
        width: ScreenUtil.getScreenW(context),
        height: ScreenUtil.getScreenH(context),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Container(
              margin: EdgeInsets.fromLTRB(15, 8, 15, 8),
              width: 100,
              decoration: BoxDecoration(
                color: Colours.app_main,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Checkbox(
                    value: allSelectrd,
                    onChanged: (value) {
                      setState(() {
                        allSelectrd = value!;
                        for (var item in dataList) {
                          item.isSelected = value;
                          if (value!) {
                            selectedDataList.add(item);
                          }
                        }
                        if (!value) {
                          selectedDataList.clear();
                        }
                      });
                    },
                  ),
                  Text(
                    "全选",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16,
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
              child: ListView.separated(
                itemBuilder: (context, index) {
                  return Container(
                    padding: EdgeInsets.all(15),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Checkbox(
                              value: dataList[index].isSelected,
                              onChanged: (value) {
                                setState(() {
                                  dataList[index].isSelected = value;
                                  bool temp = true;
                                  for (var item in dataList) {
                                    if (item.isSelected == false) {
                                      temp = false;
                                      break;
                                    }
                                  }
                                  allSelectrd = temp;
                                  if (value!) {
                                    selectedDataList.add(dataList[index]);
                                  } else {
                                    selectedDataList.remove(dataList[index]);
                                  }
                                });
                              },
                            ),
                            Text(
                              dataList[index].property != null
                                  ? "${dataList[index].expenseItem}（${dataList[index].property}）"
                                  : "${dataList[index].expenseItem}",
                              style: TextStyles.textDark16,
                            ),
                            Expanded(child: Gaps.hGap15),
                            OutlineButton(
                              padding: EdgeInsets.fromLTRB(15, 8, 15, 8),
                              child: Row(
                                children: [
                                  Icon(
                                    Icons.access_time,
                                    color: Colours.text_gray,
                                  ),
                                  Gaps.hGap10,
                                  Text(
                                      "${DateUtil.formatDate(dataList[index].dateTime, format: DateFormats.full)}"),
                                ],
                              ),
                              onPressed: () {
                                _showDateTimePicker(index);
                              },
                            )
                          ],
                        ),
                        Gaps.vGap12,
                        (dataList[index].result??[]).length > 0
                            ? Column(
                                children: (dataList[index].result??[]).map((e) {
                                  return _serviceItem(
                                    dataList[index],
                                    e,
                                    e.textEditingController,
                                  );
                                }).toList(),
                              )
                            : Gaps.empty,
                        (dataList[index].result??[]).length > 0
                            ? Gaps.vGap12
                            : SizedBox(),
                        Container(
                          color: Colors.white,
                          alignment: Alignment.topLeft,
                          child: TextField(
                            maxLines: 2,
                            autofocus: false,
                            decoration: InputDecoration(
                              hintText: "请输入备注",
                              fillColor: Colours.bg_color,
                              filled: true,
                              border: InputBorder.none,
                            ),
                            onChanged: (value) {
                              dataList[index].itemRemark = value;
                            },
                          ),
                        ),
                      ],
                    ),
                  );
                },
                separatorBuilder: (context, index) => Gaps.line,
                itemCount: dataList.length,
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _serviceItem(MedicaServiceInfo model, PendingInfo e,
      TextEditingController? controller) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Container(
          padding: EdgeInsets.fromLTRB(0, 0, 12, 0),
          margin: EdgeInsets.only(left: 15),
          width: ScreenUtil.getScreenW(context),
          decoration: BoxDecoration(
            border: Border(
              bottom: Divider.createBorderSide(context,
                  color: Colours.line, width: 1),
            ),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Text(
                '${e.subItem}',
                style: TextStyles.textDark18,
              ),
              SizedBox(
                width: 10,
              ),
              Expanded(
                child: TextField(
                  keyboardType: TextInputType.number,
                  textAlign: TextAlign.center,
                  style: TextStyles.textGray18,
                  controller: controller,
                  autofocus: false,
                  decoration: InputDecoration(
                    hintText: "输入${e.subItem}数值",
                    hintStyle: TextStyles.textGray18,
                    fillColor: Colors.white,
                    filled: true,
                    border: InputBorder.none,
                  ),
                ),
              ),
              Text(
                '${model.resultUnit ?? ''}',
                style: TextStyles.textDark18,
              )
            ],
          ),
        ),
        Container(
          padding: EdgeInsets.fromLTRB(15, 5, 15, 0),
          child: Text(
            '正常范围：${e.rangeFrom != "null" ? e.rangeFrom : ""} ~ ${e.rangeTo != "null" ? e.rangeTo : ""}',
            style: TextStyles.textGray14,
          ),
        ),
        Gaps.vGap10,
      ],
    );
  }

  ///调起时间选择器
  _showDateTimePicker(int index) {
    DatePicker.showDatePicker(
      context,
      minDateTime: DateTime.parse("1999-01-01"),
      maxDateTime: DateTime.parse("2099-01-01"),
      initialDateTime: dataList[index].dateTime,
      dateFormat: DateFormats.full,
      locale: DateTimePickerLocale.zh_cn,
      pickerTheme: DateTimePickerTheme(
        showTitle: true,
        cancel: Text("取消"),
        confirm: Text('确定'),
      ),
      pickerMode: DateTimePickerMode.time,
      onConfirm: (dateTime, List<int> index2) {
        setState(() {
          dataList[index].dateTime = dateTime;
        });
      },
    );
  }

  _fectData() {
    var map = {'ids': ids};
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.myPlanRecordBeanList}', data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            MedicaServiceModel model = MedicaServiceModel.fromJson(map['data']);
            dataList = model.rows??[];
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }
}
